#include "serial_device.h"
#include "cpc800.h"

CPC800 * cpc800_new( ) {
	return (CPC800 *) malloc(sizeof(CPC800));
}

void cpc800_free( ) {
}

int cpc800_is_goto_in_progress(CPC800 *device) {
	char data[2];
	memset((char *) data, 0, sizeof(data));
	serial_device_write(device->sdd, "L");
	serial_device_read(device->sdd, data);
	return strcmp(data, "1#") == 0;
}

void cpc800_convert_degrees_to_hexstr(float *degrees, char *hexstr) {
	float f10 = degrees[0] + (degrees[1] + (degrees[2])/60.0)/60.0;
	short unsigned int i10 = (short unsigned int) 65535.0*(f10/360.0);
	sprintf(hexstr, "%x", i10);
}

void cpc800_convert_hexstr_to_degstr(char *hexstr, char *degstr) {
	short int i10 = 0;	
	sscanf(hexstr, "%hx", &i10);
	float degrees = 360.0*(i10/65536.0);
	short int di = floor(degrees);
	short int mi = floor(60*(degrees - di));
	float si = roundf(60*(60*(degrees - di) - mi) * 100) / 100;
	sprintf(degstr, "%hd°%hd'%0.2f\"", di, mi, si);
}

void cpc800_convert_hexstr_to_hrsstr(char *hexstr, char *hrsstr) {
	short unsigned int i10 = 0;	
	sscanf(hexstr, "%hx", &i10);
	float hours = (360.0*(i10/65536.0))/15;
	short unsigned int hi = floor(hours);
	short unsigned int mi = floor(60*(hours - hi));
	float si = roundf(60*(60*(hours - hi) - mi) * 100) / 100;	
	sprintf(hrsstr, "%hdh%hdm%0.2fs", hi, mi, si);
}

void cpc800_convert_hours_to_hexstr(float *hours, char *hexstr) {
	float f10 = hours[0] + (hours[1] + (hours[2])/60.0)/60.0;
	short unsigned int i10 = (short unsigned int) 65535.0*(15*f10)/360.0;
	sprintf(hexstr, "%x", i10);
}

void cpc800_get_ra_dec(CPC800 *device, char *ra, char *dec) {
	char data[10] = "34AB,C001#";
	char hexstrs[2][12];
	char *pch = NULL;
	int c = 0;
	memset((char *) data, 0, sizeof(data));
	serial_device_write(device->sdd, "E");
	serial_device_read(device->sdd, (void *) data);
	pch = strtok(data, ",#");
	while(pch != NULL) {
		strcpy(hexstrs[c++], pch);
		pch = strtok(NULL, ",#");
	}
	cpc800_convert_hexstr_to_hrsstr(hexstrs[0], ra);
	cpc800_convert_hexstr_to_degstr(hexstrs[1], dec);
}

void cpc800_goto_ra_dec(CPC800 *device, float *dra, float *ddec) {
	char data[10], hra[4], hdec[4];
	memset((char *) data, 0, sizeof(data));
	memset((char *) hra, 0, sizeof(hra));
	memset((char *) hdec, 0, sizeof(hdec));
	cpc800_convert_hours_to_hexstr(dra, hra);
	cpc800_convert_degrees_to_hexstr(ddec, hdec);
	sprintf(data, "R%s,%s", hra, hdec);
	serial_device_write(device->sdd, data);
}
